<template>
    <div class="chat-container">
        <TmallNavBar>
            <template #left><i class="icon iconfont icon-zuojiantou"></i></template>
            <template #default>nodejs socket.io聊天</template>
        </TmallNavBar>

        <!-- 消息区域开始 -->
        <div class="content-wrap">
            <div v-for="(item, index) in messageList" :key="index">
                <!-- 发消息区域开始 -->
                <div class="msg-to-wrap" v-if="item.from_uid != uid">
                    <div class="avatar-box">
                        <img
                            src="@/assets/images/avatar.png"
                            mode="scaleToFill"
                        />
                    </div>
                    <div class="content-box">
                        <p class="time">{{ formatTime(item.create_time, 'HH:mm') }}</p>
                        <p class="msg-panel">{{ item.content }}</p>
                    </div>
                </div>
                <!-- 发消息区域结束 -->

                <!-- 接收消息区域开始 -->
                <div class="msg-from-wrap" v-if="item.from_uid == uid">
                    <div class="content-from-box">
                        <div class="content-from-panel">
                            <div class="time">{{ formatTime(item.create_time, 'HH:mm') }}</div>
                            <div class="msg-panel">{{ item.content }}</div>
                        </div>
                    </div>

                    <div class="avatar-from-box">
                        <img
                            src="@/assets/images/avatar.png"
                            mode="scaleToFill"
                        />
                    </div>
                </div>
            </div>
            <!-- 接收消息区域结束 -->
        </div>
        <!-- 消息区域结束 -->

        <!-- 操作区域开始 -->
        <div class="opt-wrap">
            <van-field
                v-model="params.to_uid"
                center
                clearable
                placeholder="发送至用户"
            >
                <template #button>
                    <van-button color="#27BA9B" size="small" type="primary" @click="handleCloseConn">断开连接</van-button>
                </template>
            </van-field>
            <van-field
                v-model="params.content"
                center
                clearable
                placeholder="请输入消息"
            >
                <template #button>
                    <van-button color="#27BA9B" size="small" type="primary" @click="handleSendMessage">发送消息</van-button>
                </template>
            </van-field>
        </div>
        <!-- 操作区域结束 -->
    </div>
</template>

<script lang="ts" setup>
import dayjs from 'dayjs'
import { v4 as uuidv4 } from 'uuid'
import { formatTime } from '@/utils/tools'
import { nextTick, onMounted, reactive, ref } from 'vue'
import type { MessageListParam, SendMessageParams } from '@/types/chat'
import { cloneDeep } from 'lodash'
// 使用 vant 组件
// @ts-ignore
import { showLoadingToast, showToast, showFailToast } from 'vant'
import { initSocketIO, loadingInstance, messageList, setQuery, socket } from '@/utils/socketIO'
import { reqMessageListAPI } from '@/apis/message'

// 用户Id
const uid = ref(uuidv4())

// 用户token
const token = ref(uuidv4())

// 发消息参数
const params = reactive<SendMessageParams>({
    id: '',
    from_uid: uid.value,
    to_uid: '',
    event_type: 'chat',
    type: 1,
    content: '',
    image_url: '',
    status: 1,
    is_read: 0,
    create_time: dayjs().format('YYYY-MM-DD HH:mm:ss')
});

// 消息列表参数
const messageListParams = reactive<MessageListParam> ({
    from_uid: uid.value,
    to_uid: uid.value,
    event_type: "chat",
    status: 1,
    page: 1
})

// 消息数量
const total = ref(0)

// ------------------ 页面挂载完毕 ------------------
onMounted(async () => {

    // 获取消息列表
    // await getMessageList()

    setQuery({
        uid: uid.value,
        username: '杀戮天君',
        token: token.value,
        group: 'trident'
    })

    initSocketIO(import.meta.env.VITE_NODE_SOCKET_IO_SERVER)
})



// -------------- 处理发送消息功能开始 --------------
const handleSendMessage = async () => {
    if (params.content == '') {
        showToast('请输入消息')
        return false
    }
    loadingInstance.value.open()
    console.log('handleSendMessage = ')
    console.log('params =', params)
    const message = cloneDeep(params)
    messageList.value.push(message)
    console.log('message =', message)
    socket.value.emit('chat', message)
    params.content = ''


    // 始终显示新一条消息
    await nextTick()
    window.scrollTo(0, document.body.scrollHeight)
    loadingInstance.value.close()
}
// -------------- 处理发送消息功能结束 --------------



// -------------- 处理关闭连接功能开始 --------------
const handleCloseConn = () => {
    socket.value.close()
}
// -------------- 处理关闭连接功能结束 --------------



// -------------- 获取消息列表功能结束 --------------
const getMessageList = async () => {
    const result = await reqMessageListAPI(messageListParams)
    let messages = result.data.messages != null ? result.data.messages : []
    total.value = result.data.total
    console.log('result =', result);
    messageList.value.push(...messages)
}
// -------------- 获取消息列表功能结束 --------------
</script>

<style scoped lang="scss">
.chat-container {
    padding: 50px 0 100px 0;
    .content-wrap {
        padding: 0 10px;
        // 发消息区域开始
        .msg-to-wrap {
            margin: 15px 0;
            display: flex;
            .avatar-box {
                margin-right: 5px;
                img {
                    width: 40px;
                    height: 40px;
                }
            }
            .content-box {
                .time {
                    color: gainsboro;
                    font-size: 14px;
                    padding-bottom: 5px;
                }
                img {
                    width: 100px;
                    height: 100px;
                    border-radius: 5px;
                }

                .msg-panel {
                    background-color: #fff;
                    padding: 10px;
                    max-width: 280px;
                    border-radius: 8px;
                }
            }
        }
        // 发消息区域结束


        // 接收消息区域开始
        .msg-from-wrap {
            margin: 40px 0;
            display: flex;
            justify-content: flex-end;
            .content-from-box {
                display: flex;
                justify-content: flex-end;
                .content-from-panel {
                    .time {
                        display: flex;
                        justify-content: flex-end;
                        color: gainsboro;
                        font-size: 14px;
                        padding-bottom: 15px;
                    }

                    img {
                        width: 100px;
                        height: 100px;
                        border-radius: 5px;
                    }

                    .msg-panel {
                        background-color: #fff;
                        padding: 10px;
                        line-height: 22px;
                        max-width: 300px;
                        border-radius: 10px;
                    }
                }
            }
            .avatar-from-box {
                margin-left: 5px;
                img {
                    width: 40px;
                    height: 40px;
                }
            }
        }
        // 接收消息区域结束
    }

    .opt-wrap {
        position: fixed;
        bottom: 0;
        width: 100%;
    }
}
</style>